package com.roamer.audition.web.security.handler;

import cn.hutool.json.JSONUtil;
import com.roamer.rest.IErrorCode;
import com.roamer.rest.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局认证异常处理
 *
 * @author roamer
 * @version v1.0
 * @date 2020/4/21 16:18
 */
@Slf4j
public class GlobalAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JSONUtil.toJsonStr(RestResult.failure(IErrorCode.C40100)));
    }
}
